package servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userId=request.getParameter("id");
        String userPassword=request.getParameter("pwd");
        UserService userService=new UserServiceImpl();
        User user=userService.queryStudentById(userId);
        request.getSession().setAttribute("logining","true"); //标记正在登录
        if(user!=null){
            if(user.getUserPassword().equals(userPassword)){
                request.getSession().setAttribute("user",user);//登录成功 将实体User保存到session域中
                if(user.getUserId().equals("admin"))
                    request.getRequestDispatcher("menu.jsp").forward(request,response);
                else{
                    request.getRequestDispatcher("menuStu.jsp").forward(request,response);
                }
            }else{
                response.sendRedirect("login.jsp");
            }
        }else{
            response.sendRedirect("login.jsp");
        }
    }
}
